#!/usr/bin/python
# -*- coding: utf-8 -*
from stackDemo import Stack


def infixtopostfix(infix):
    prec={'(': 1, '+': 2, '-': 2, '*': 3, '/': 3}
    infix_list = infix.split()
    s=Stack()
    postfix_list = []
    for item in infix_list:
        if item in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" or item in "0123456789":
            postfix_list.append(item)
        elif item == '(':
            s.push(item)
        elif item == ')':
            top = s.pop()
            while top != '(':
                postfix_list.append(top)
                top = s.pop()
        else:
            while not s.isEmpty() and (prec[item] <= prec[s.peek()]):
                top = s.pop()
                postfix_list.append(top)
            s.push(item)
    while not s.isEmpty():
        postfix_list.append(s.pop())
    return ' '.join(postfix_list)


print(infixtopostfix("A * B + C * D"))
print(infixtopostfix("( A + B ) * C - ( D - E ) * ( F + G )"))
print(infixtopostfix("( A + B ) * C"))
print(infixtopostfix("( A + B ) * ( C + D )"))
